package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.config.RedisConfiguration;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.GaoDemapProperties;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.CheckOutOfRangeUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RouteAdminMapper routeAdminMapper;
    @Autowired
    private RouteMapper routeMapper;
    @Autowired
    private RoutePlanningMapper routePlanningMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private GaoDemapProperties gaoDemapProperties;
    @Autowired
    private CheckOutOfRangeUtil checkOutOfRangeUtil;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WebSocketServer webSocketServer;

    private static final Long ADMIN_ID = 1L;
    private  static final int MAX_ORDER_DISTANCE_METERS = 5000;
    /**
     * 判断地址是否超出范围
     * @param key 高德Key
     * @param city 指定查询的城市
     * @param UserAddress 订单地址
     */
    private void checkOutOfRange(String key, String city, String UserAddress, AddressBook addressBook) {
        // 获得商家地址坐标
        RouteAdmin routeAdmin = routeAdminMapper.getById(ADMIN_ID);
        String AdminLocation = routeAdmin.getLocation();
        // 获得订单地址坐标
        JSONObject jsonObjectLocation = checkOutOfRangeUtil.getlocation(UserAddress, city, key);
        // 解析地址
        String UserLocation = Location(jsonObjectLocation);
        // 路径规划
        JSONObject jsonObjectRoute = checkOutOfRangeUtil.getcheckOutOfRange(key, AdminLocation, UserLocation);
        // 解析路径规划
        Route(jsonObjectRoute,addressBook);
    }

    /**
     *  解析路径坐标
     * @param jsonObject 请求返回的json对象
     * @return 路径坐标
     */
    private String Location(JSONObject jsonObject){
        JSONArray geocodes = jsonObject.getJSONArray("geocodes");
        if (geocodes == null || geocodes.isEmpty()) {
            throw new OrderBusinessException(MessageConstant.STORE_ADDRESS_RESOLUTION_FAILED);
        }
        // 取第一个地理编码结果（通常是最匹配的）
        JSONObject firstGeocode = geocodes.getJSONObject(0);
        // 获取经纬度坐标
        String location = firstGeocode.getString("location");
        return location;
    }

    /**
     * 路径规划
     * @param jsonObjectRoute 请求返回的json对象
     */
    private void Route(JSONObject jsonObjectRoute, AddressBook addressBook){
        // 解析route整体信息
        JSONObject routeObj = jsonObjectRoute.getJSONObject("route");
        JSONArray pathsArray = routeObj.getJSONArray("paths");
        JSONObject pathObj = pathsArray.getJSONObject(0);  // 只取第一个方案（一般就一个）

        // 创建Route对象
        Route route = new Route();
        route.setUserId(addressBook.getUserId());    // 当前用户ID
        route.setAdminLocation(routeObj.getString("origin"));
        route.setUserLocation(routeObj.getString("destination"));
        route.setDistance(Long.parseLong(pathObj.getString("distance")));
        // 判断配送距离是否超过5000米
        if(route.getDistance() > MAX_ORDER_DISTANCE_METERS){
            //配送距离超过5000米
            throw new OrderBusinessException(MessageConstant.OUT_OF_RANGE);
        }
        // 解析steps数组
        JSONArray stepsArray = pathObj.getJSONArray("steps");
        List<RoutePlanning> routePlanningList = new ArrayList<>();

        for (int i = 0; i < stepsArray.size(); i++) {
            JSONObject stepObj = stepsArray.getJSONObject(i);

            RoutePlanning routePlanning = new RoutePlanning();
            routePlanning.setSerialNumber((long) i + 1);  // 序号从1开始

            routePlanning.setInstruction(stepObj.getString("instruction"));
            routePlanning.setOrientation(stepObj.getString("orientation"));
            routePlanning.setRoadName(stepObj.getString("road_name"));
            routePlanning.setStepDistance(stepObj.getString("step_distance"));

            // cost对象里取duration（如果有）
            JSONObject costObj = stepObj.getJSONObject("cost");
            if (costObj != null) {
                routePlanning.setDuration(costObj.getString("duration"));
            }

            // navi对象里的信息
            JSONObject naviObj = stepObj.getJSONObject("navi");
            if (naviObj != null) {
                routePlanning.setAction(naviObj.getString("action"));
                routePlanning.setAssistantAction(naviObj.getString("assistant_action"));
                routePlanning.setWalkType(naviObj.getString("walk_type"));
            }

            routePlanning.setPolyline(stepObj.getString("polyline"));

            routePlanningList.add(routePlanning);
        }
        // 存储路径坐标、路径规划信息
        String routeKey = "route:order:" + addressBook.getUserId();
        String stepsKey = "route:order:" + addressBook.getUserId() + ":steps";
        set(routeKey, JSON.toJSONString(route));  // 存整个Route对象
        set(stepsKey, JSON.toJSONString(routePlanningList));  // 存所有steps
    }

    /**
     * 加入缓存
     * @param key key
     * @param value value
     */
    public void set(String key, String value) {
        redisTemplate.opsForValue().set(key, value, 1, TimeUnit.HOURS);
    }

    /**
     * 获取缓存
     * @param key key
     * @return object
     */
    public String get(String key) {
        String object = (String) redisTemplate.opsForValue().get(key);
        return object;
    }
    /**
     * 用户下单
     *
     * @param ordersSubmitDTO 用户端订单提交数据传输模型
     * @return orderSubmitVO
     */
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 处理各种业务异常(地址簿为空、购物车数据为空)
        AddressBook addressBook = addressBookMapper.getByid(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        String UserAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        Long userId = addressBook.getUserId();
        // 判断地址是否超出范围
        checkOutOfRange(gaoDemapProperties.getKey(),gaoDemapProperties.getCity(),UserAddress,addressBook);
        // 判断购物车数据是否为空
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build();
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 向订单表插入1条数据
        // 拷贝
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 封装信息
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        String number = System.currentTimeMillis() + BaseContext.getCurrentId() + "";
        orders.setNumber(number);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setAddress(UserAddress);
        orderMapper.insert(orders);
        // 向订单明细表插入n条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        shoppingCartList.forEach(Cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(Cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        orderDetailMapper.insertOrders(orderDetailList);
        // 清空购物车数据
        ShoppingCart OldShoppingCart = new ShoppingCart();
        OldShoppingCart.setUserId(BaseContext.getCurrentId());
        shoppingCartMapper.deleteByUserId(OldShoppingCart);
        // 封装vo返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO 订单支付传输模型
     * @return orderPaymentVO
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(ordersPaymentDTO.getOrderNumber(), userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );

        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 订单号
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 订单分页查询
     *
     * @param page     页码
     * @param pageSize 每页记录数
     * @param status   订单状态
     * @return PageResult
     */
    public PageResult pageQuery(int page, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(page, pageSize);
        // 设置分页查询条件，根据用户id和订单状态查询
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        // 执行分页查询
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();
        // 查询出订单明细，并封装入OrderVO进行响应
        if (ordersPage != null && ordersPage.getTotal() > 0) {
            for (Orders orders : ordersPage) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                // OrderVo,继承了 Orders，并且封装了订单菜品信息、订单明细
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                orderVOList.add(orderVO);
            }
        }
        return new PageResult(ordersPage.getTotal(), orderVOList);
    }

    /**
     * 订单详情
     *
     * @param id 订单id
     * @return OrderVO
     */
    public OrderVO orderDetail(Long id) {
        // 根据订单id查询订单数据
        Orders orders = orderMapper.getById(id);
        // 根据订单id查询订单明细数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 将查询结果封装到OrderVO中
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id 订单id
     */
    @Transactional
    public void cancel(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单【直接取消】    3已接单 4派送中 5已完成【客户无法取消】 6已取消
        if (ordersDB.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    ordersDB.getNumber(), //商户订单号
//                    ordersDB.getNumber(), //商户退款单号
//                    new BigDecimal(0.01),//退款金额，单位 元
//                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }

        // 更新订单状态、取消原因、取消时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单
     *
     * @param id 订单id
     */
    public void repetition(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream()
                .map(x -> {
                    ShoppingCart shoppingCart = new ShoppingCart();

                    // 将原订单详情里面的菜品信息重新复制到购物车对象中,并且排除 id 属性
                    BeanUtils.copyProperties(x, shoppingCart, "id");
                    shoppingCart.setUserId(userId);
                    shoppingCart.setCreateTime(LocalDateTime.now());
                    // 将购物车实体类返还到流中，组成新的集合
                    return shoppingCart;
                }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertshoppingCars(shoppingCartList);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO 查询条件
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        List<OrderVO> orderVOList = getOrderVOList(page);

        return new PageResult(page.getTotal(), orderVOList);
    }

    /**
     * 将分页后的订单数据封装到OrderVO集合中
     *
     * @param page 分页后的订单数据
     * @return orderVOList
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }
        return orderVOList;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders 订单实体类
     * @return orderDishes
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3;青椒炒肉*2;）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /**
     * 订单统计
     *
     * @return OrderStatisticsVO
     */
    public OrderStatisticsVO statistics() {
        // 统计待派送订单数量
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        // 统计派送中订单数量
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        // 统计待接单订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO
                .builder()
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .toBeConfirmed(toBeConfirmed)
                .build();
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO 接单参数
     */
    @Transactional(rollbackFor = Exception.class)
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersConfirmDTO, orders);
        orderMapper.update(orders);
        // 插入路线表
        Orders ordersUserId = orderMapper.getById(ordersConfirmDTO.getId());
        String routeKey = "route:order:" + ordersUserId.getUserId();
        String routeJson = get(routeKey);
        Route routeFromRedis = JSON.parseObject(routeJson, Route.class);
        routeFromRedis.setOrdersNumber(ordersUserId.getNumber());
        routeMapper.inster(routeFromRedis);
        // 插入路线规划表
        String stepsKey = "route:order:" + ordersUserId.getUserId() + ":steps";
        String stepsJson = get(stepsKey);
        List<RoutePlanning> stepsFromRedis = JSON.parseArray(stepsJson, RoutePlanning.class);
        for (RoutePlanning routePlanning : stepsFromRedis) {
            routePlanning.setRouteId(routeFromRedis.getId());
            log.info("routePlanning:{}", routePlanning);
        }
        log.info("stepsFromRedis:{}", stepsFromRedis);
        routePlanningMapper.insertBatch(stepsFromRedis);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO 拒绝订单参数
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 判断是否付款，如果付款，则需要退款
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());
        // 判断订单状态，如果不是待接单状态或为空则无法拒单
        if (ordersDB == null || ordersDB.getPayStatus() == Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
//        if (ordersDB.getPayStatus() == Orders.PAID){
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }
        Orders orders = Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersRejectionDTO.getRejectionReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 管理员取消订单
     * @param id 订单id
     */
    public void admincancel(OrdersCancelDTO ordersCancelDTO) {
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());
        // 判断不为空
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
//        if (ordersDB.getPayStatus() == Orders.PAID){
//            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
//        }
        Orders orders = Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id 订单id
     */
    public void delivery(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        // 判断订单是否存在
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 判断订单状态，是否为待派送状态
        if (ordersDB.getStatus() != Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id 订单id
     */
    public void complete(Long id) {
        Orders ordersDB = orderMapper.getById(id);
        // 判断订单是否存在
        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 判断只有派送中的订单才可以完成
        if (ordersDB.getStatus() != Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);
    }

    /**
     * 用户催单
     *
     * @param id
     */
    public void reminder(Long id) {
        // 查询订单是否存在
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
